<template>
  <div class="login-bg">
    <div class="login-card">
      <div class="login-pane">
        <div class="login-title">后台登陆</div>

        <el-form ref="form" :model="formData" :rules="rules" label-position="top" @submit.prevent="onFormSubmit">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username" placeholder="输入登陆用户名" />
          </el-form-item>

          <el-form-item label="登陆密码" prop="password">
            <el-input v-model="formData.password" type="password" placeholder="输入登陆密码" />
          </el-form-item>

          <el-form-item style="margin-top: 40px">
            <el-button type="primary" style="width: 100%" native-type="submit" :loading="subIng">确认登陆</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { adminLogin } from '@/services/auth.service'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/store/auth'
import { useRouter } from 'vue-router'

interface FormData {
  username?: string;
  password?: string;
}

export default defineComponent({
  name: 'login',
  setup () {
    const router = useRouter()
    const form = ref(null)
    const formData = ref<FormData>({})
    const subIng = ref(false)
    const authStore = useAuthStore()
    const rules = ref({
      username: [{ required: true, message: '请输入用户名' }],
      password: [{ required: true, message: '请输入登陆密码' }]
    })

    // 提交登陆
    const onFormSubmit = async () => {
      await (form.value as any).validate()
      subIng.value = true
      try {
        const resp = await adminLogin(formData.value as any)
        authStore.saveAuthInfo(resp)
        await router.push('/')
      } catch (e) {
        ElMessage.error(e.message)
      } finally {
        subIng.value = false
      }
    }
    return {
      form,
      formData,
      rules,
      subIng,
      onFormSubmit
    }
  }
})
</script>

<style scoped lang="scss">
.login-bg {
  background-image: url("../../../assets/login_bg.jpg");
  background-size: 100% 100%;
}
.login-card {
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  .login-title {
    border-bottom: solid 1px #f2f2f2;
    padding-bottom: 20px;
    margin-bottom: 20px;
    font-weight: bold;
    color: #666;
  }
  .login-pane {
    background: #fff;
    width: 440px;
    margin: 0 auto;
    padding: 20px;
    border: solid 1px #f2f2f2;
    box-shadow: 2px 1px 4px rgba(0,0,0,0.45);
  }
}
</style>
